from PIL import Image
import os
import numpy as np
import bisect




def crop_image():
    """ First we cut the image label, 50 pixel at bottom"""
    img = Image.open(path + image_file)
    width, height = img.size
    
    box = (0, 0, width, height-50)
    area = img.crop(box)
    
    area.convert('RGB').save(path + image_name + '_croped.jpg', 'jpeg')
    

def find_background_treshold():
    """Finds the treshold to extract background colour. Return treshold as value"""
    # First create an histogramm.
    image = Image.open(path + image_file).convert('L')

    histo = image.histogram()
    histo_lst = []
    for i in histo:
      histo_lst.append(i)
    
    # Get the maximum peak, this should be the background. Ignore peaks > 200 need to be implement!!!
    max_value =  max(histo_lst[1:])
    # Get the histogram position of the peak.
    max_pos = histo_lst.index(max_value)
    #------------------------------------------------------------------------
    # Calculate the local minima
    a=np.array(histo_lst, dtype=np.float)
    
    gradients=np.diff(a)
    maxima_num=0
    minima_num=0
    max_locations=[]
    min_locations=[]
    count=0
    for i in gradients[:-1]:
        count+=1
    
        if ((cmp(i,0)>0) & (cmp(gradients[count],0)<0) & (i != gradients[count])):
            maxima_num+=1
            max_locations.append(count)     
    
        if ((cmp(i,0)<0) & (cmp(gradients[count],0)>0) & (i != gradients[count])):
            minima_num+=1
            min_locations.append(count)
        
    #------------------------------------------------------------------------
    # Get the next local maxima after the highest peak. This is the treashold.
    index= bisect.bisect_right(min_locations, max_pos)
    if index == 0: # there's not a "next lower value"
        raise NotImplementedError # you must decide what to do here
    else:
        return min_locations[index]

def get_pixels(treshold):
    """Get image pixels and replace all pixel below treshold with 0 to remove the background noise."""
    im = Image.open(path + image_file)
    if im.mode != 'L': 
        im = im.convert('L')
    pixels = list(im.getdata())
    outpixels = []
    counter = 0
    w, h = im.size
    for i in pixels:
        if i < treshold:
            i = 0
        if counter == int(w):
            counter = 0
        counter += 1
        outpixels.append(i)
    
    outimg = Image.new('L', (w, h)) 
    outimg.putdata(outpixels)
    outimg.save(path + image_name + '_extracted_background.jpg')
        
def get_lanes():
    """Calculates sum of coloumns and draw a plot. Peaks are lanes."""
    treshold = find_background_treshold()
    get_pixels(treshold)
    
    path = '/home/stefanie/workspace/Gel image analyse/Final/Images/'
    array = np.asarray(Image.open(path + image_name + '_extracted_background.jpg'))
    
    im = Image.open(path + image_name + '_extracted_background.jpg')
    w, h = im.size
    y = array[0].sum()
    lanes = []
    for x in range(w):
        try:
            z = array[:, x].sum()
            lanes.append(z)
        except:
            pass

#    pyplot.plot(lanes)
#    pyplot.show()
    print lanes.count(0), sum(lanes)

    
    

    
## First we crop the image, remove label at bottom
#image_file = 'test.tif'
#image_name = image_file.split('.')[0]
#
#crop_image()
#get_lanes()
#
## Now try to straighten the image by rotatation
#    
#im1 = Image.open(image).convert('L')
#im2 = im1.rotate(degree)
##im2.show()
#im2.save(image + '_rotated_' + str(degree) + '.jpg')

original_image = 'test.tif'
path = '/home/stefanie/workspace/Gel image analyse/Final/Images/'



for i in range(-10, 11, 1):
    degree = i/2.0
    print degree
    im1 = Image.open(original_image).convert('L')
    im2 = im1.rotate(degree)
    im2.save(path + original_image.split('.')[0] + '_' + str(degree) + '.jpg')
    
    image_file = original_image.split('.')[0] + '_' + str(degree) + '.jpg'
    image_name = image_file.split('.')[0]
    crop_image()
    get_lanes()
    